package DBModule;

import java.io.IOException;
import java.sql.*;
import java.util.Collection;
import java.util.Iterator;

import Test.Exception.FactoryException;

public class DBManager{
	// 驱动名
	private static String dbDriveName="com.mysql.jdbc.Driver";
	// mysql URL地址
	private static String dbUrl="jdbc:mysql://localhost:3306/Test?user=TestManager&password=123456&characterEncoding=utf-8";
	static {
		try{
			Class.forName(dbDriveName);
		}catch (Exception e){
			e.printStackTrace();
			System.exit(-1);
		}
	}
	
	private static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(dbUrl);
	}
	
	private static void close(Connection conn){
		try{conn.setAutoCommit(true);}
		catch (Exception e){e.printStackTrace();}
		try{conn.close();}
		catch (Exception e){e.printStackTrace();}
	}
	
	/**
	 * 更新，失败则在标准错误输出流打印相应信息
	 * @param updater	更新接口
	 * @param opt		待更新的元素
	 */
	public static <T> void update(DBUpdater<T> updater, T... opt) throws Exception{
		Connection conn = null;
		try{
			conn = getConnection();
			conn.setAutoCommit(false);
			updater.update(conn, opt);
			conn.commit();
		}catch (Exception exp){
//			exp.printStackTrace(System.out);
			try {
				conn.rollback();
				conn.commit();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
			throw exp;
		}finally{
			close(conn);
		}
	}
	
	/**
	 * 查询
	 * @param querier	查询接口
	 * @param keys		键
	 * @return			成功返回迭代器，失败返回null并在标准错误输出流打印相应信息
	 * @throws SQLException 
	 * @throws FactoryException 
	 * @throws IOException 
	 */
	public static<T> Collection<T> query(DBQuerier<T> querier, Object... keys) throws SQLException, IOException, FactoryException {
		Connection conn = null;
		Collection<T> ret = null;
		try{
			conn = getConnection();
			ret = querier.query(conn, keys);
		}/*catch (Exception e){
			e.printStackTrace();
			throw e;
		}*/finally{
			close(conn);
		}
		return ret;
	}
}
















